package com.example.blog.service.AllToAll;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class ExcelToWordService {

    /**
     * 将Excel文档转换为Word文件
     * @param excelPath Excel文件路径
     * @param wordPath 生成的Word文件路径
     */
    public void convertExcelToWord(String excelPath, String wordPath) {
        try (InputStream excelFile = Files.newInputStream(Paths.get(excelPath));
             Workbook workbook = new XSSFWorkbook(excelFile);
             XWPFDocument document = new XWPFDocument();
             OutputStream out = Files.newOutputStream(Paths.get(wordPath))) {

            Sheet sheet = workbook.getSheetAt(0);
            // 遍历Excel的行和单元格并添加到Word文档中
            for (Row row : sheet) {
                XWPFParagraph paragraph = document.createParagraph();
                for (Cell cell : row) {
                    XWPFRun run = paragraph.createRun();
                    run.setText(cell.toString() + "\t");
                }
            }
            document.write(out);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
